package com.logjun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.logjun.reggie.common.R;
import com.logjun.reggie.entity.Employee;
import com.logjun.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    //@Cacheable(value = "employeeOneCache",key = "'employee'+employee.getUsername()")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //获取密码
        String password = employee.getPassword();
        //密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工登出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    //@CacheEvict(value = "employeeOneCache",allEntries = true)
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     *新增员工
     */
    @PostMapping
    @CacheEvict(value = "employeeCache",allEntries = true)
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee){
        log.info("新增员工信息：{}",employee.toString());
        //设置初始化密码，进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        /*//设置创建时间和更新时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获取session中的用户id，设置创建人id和更新人id
        Long eID = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(eID);
        employee.setUpdateUser(eID);*/
        //调用服务
        employeeService.save(employee);
        return R.success("新增用户成功");

    }

    /**
     * 员工信息分页查询
     */
    @GetMapping("/page")
    @Cacheable(value = "employeeCache",key = "'employeePage'+#page+'_'+#pageSize+'_'+#name")
    public R<Page<Employee>> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页查询器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Employee::getCreateTime);
        //执行查询
        employeeService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 员工信息更新*/
    @PutMapping
    @CacheEvict(value = "employeeCache",allEntries = true)
    public R update(HttpServletRequest request,@RequestBody Employee employee){
        log.info("员工信息：{}",employee.toString());
        /*employee.setUpdateTime(LocalDateTime.now());
        //设置更新人id，从session获取当前用户的id。
        Long id = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(id);*/
        employeeService.updateById(employee);
        return R.success("员工更新成功");
    }

    /**
     * 根据id查询员工信息
     */
    @GetMapping("/{id}")
    @Cacheable(value = "employeeCache",key = "'employee'+#id")
    public R getById(@PathVariable Long id) {
        log.info("根据员工id查询数据...");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("查询失败");
    }

}
